#include "QTreeViewMdTitle.h"
#include "ui_QTreeViewMdTitle.h"
#include <QMenu>
#include <QRegularExpression>
#include <QDebug>
#include <QInputDialog>
#include <QFileInfo>
QTreeViewMdTitle::QTreeViewMdTitle(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QTreeViewMdTitle)
{
    ui->setupUi(this);
    tocModel = new QStandardItemModel(0, 1, this);
    tocModel->setHorizontalHeaderLabels({"文件","大小"});
    ui->ui_tree->setModel(tocModel);
    //增加右键菜单
    ui->ui_tree->setContextMenuPolicy(Qt::CustomContextMenu);
}

QTreeViewMdTitle::~QTreeViewMdTitle()
{
    delete ui;
}


void QTreeViewMdTitle::get_markdown_title_tree(QString markdownText)
{
    tocModel->clear();
    tocModel->setHorizontalHeaderLabels({"文件","大小"});
    QRegularExpression headingRegex("^(#{1,6})\\s+(.*)$", QRegularExpression::MultilineOption);
    QRegularExpressionMatchIterator matchIterator = headingRegex.globalMatch(markdownText);

    QList<QStandardItem*> parentItems;
    parentItems.append(nullptr);
    int title_cnt = 0;
    QDEBUG << markdownText;
    while (matchIterator.hasNext())
    {
        QRegularExpressionMatch match = matchIterator.next();
        QString title = match.captured(2);
        int level = match.captured(1).length();

        // get parrent items
        while (parentItems.size() > level) {
            parentItems.removeLast();
        }
        while (parentItems.size() < level) {
            parentItems.append(nullptr);
        }

        QStandardItem *parent = parentItems[level - 1];
        QString itemText = title; //获取目录地标题
        QStringList list_title = itemText.split("+:");
        QStandardItem *item = new QStandardItem(list_title.at(0));
        QList<QStandardItem *> parentItem1_sum;
        parentItem1_sum.clear();
        parentItem1_sum.append(item);
        if(list_title.size() > 1)
        {
            QStandardItem *item2 = new QStandardItem(list_title.at(1)); //文件大小
            parentItem1_sum.append(item2);
        }
        if (parent) {
            parent->appendRow(parentItem1_sum);
        } else {
            tocModel->appendRow(parentItem1_sum);
        }

        // update parrent items
        if (parentItems.size() == level) {
            parentItems.append(parentItem1_sum);
        } else {
            parentItems[level]->appendRow(parentItem1_sum);
        }
        title_cnt ++;
        QDEBUG << title_cnt;
    }
    ui->ui_tree->expandAll();
    for (int i = 0; i < ui->ui_tree->model()->columnCount(); ++i)
    {
        ui->ui_tree->resizeColumnToContents(i);
    }
}

void QTreeViewMdTitle::add_file_title_tree(QString basename)
{
    if(basename == "")
    {
        QDEBUG << "file path is empty";
    }
    QStringList str_path = basename.split("/");
    QStandardItem * root = new QStandardItem(str_path.at(0));
    for(int i = 1; i < str_path.size(); i++)
    {
        if(i == str_path.size() - 1) // 增加文件大小的显示
        {
            QList<QStandardItem *> parentItem1_sum;
            parentItem1_sum.clear();
            QStringList list_title = str_path.at(i).split("+:");
            parentItem1_sum.append(new QStandardItem(list_title.at(0)));
            if(list_title.size() >= 1)
            {
                parentItem1_sum.append(new QStandardItem(list_title.at(1))); //不足时不加载
            }
            root->appendRow(parentItem1_sum);
        }
        else
        {
            root->appendRow(new QStandardItem(str_path.at(i)));
        }
    }


    tocModel->appendRow(root); //增加显示


}

void QTreeViewMdTitle::scan_delet_same_item()
{
    //删除重复构建项
    delet_same_item(tocModel->invisibleRootItem());
    ui->ui_tree->expandAll();
}

void QTreeViewMdTitle::delet_same_item(QStandardItem *parent)
{
    if (!parent) return;

    // 1. 先处理所有子节点的子节点（深层优先）
    for (int i = 0; i < parent->rowCount(); ++i) {
        delet_same_item(parent->child(i));
    }

    // 2. 收集当前节点下所有子节点的名称和索引
    QMap<QString, QList<int>> nameToRows;
    for (int i = 0; i < parent->rowCount(); ++i) {
        QString name = parent->child(i)->text();
        nameToRows[name].append(i);
    }

    // 3. 处理重复项（逆序遍历，避免删除元素后索引错乱）
    QList<QString> names = nameToRows.keys();
    for (const QString &name : names) {
        QList<int> rows = nameToRows[name];
        if (rows.size() <= 1) continue; // 没有重复项

        // 保留第一个节点作为主节点，其他作为重复节点
        int mainRow = rows.first();
        QStandardItem *mainItem = parent->child(mainRow);

        // 逆序处理其他重复节点（关键修复：从后往前删，避免索引偏移）
        for (int i = rows.size() - 1; i >= 1; --i) {
            int duplicateRow = rows[i];
            QStandardItem *duplicateItem = parent->child(duplicateRow);

            // 将重复节点的子节点移动到主节点
            while (duplicateItem->rowCount() > 0) {
                QList<QStandardItem*> children = duplicateItem->takeRow(0);
                mainItem->appendRow(children);
            }

            // 删除重复节点（此时索引不会影响前面的节点）
            parent->removeRow(duplicateRow);
        }

        // 对合并后的主节点再次检查（防止移动子节点后产生新重复）
        delet_same_item(mainItem);
    }
}

void QTreeViewMdTitle::on_ui_tree_customContextMenuRequested(const QPoint &pos)
{
    //qDebug() << pos;
    QMenu menu;
    // 获取点击位置
    QPoint globalPos = ui->ui_tree->mapToGlobal(pos);
    //添加action
    QAction *action1 = new QAction(QStringLiteral("加载"));
    QAction *action2 = new QAction(QStringLiteral("存储"));
    QAction *action3 = new QAction(QStringLiteral("列举"));

    QModelIndex index2 = tocModel->index(cur_index.row(), 1, cur_index.parent());
    QString     s_size = tocModel->data(index2,Qt::DisplayRole).toString();

    action1->setEnabled((s_size != "")); //只加载文件


    menu.addAction(action1);
    menu.addAction(action2);
    menu.addAction(action3);

    connect(action1,&QAction::triggered,this,&QTreeViewMdTitle::load_slot);
    connect(action2,&QAction::triggered,this,&QTreeViewMdTitle::save_slot);
    connect(action3,&QAction::triggered,this,&QTreeViewMdTitle::list_slot);


    menu.exec(globalPos);
}

void QTreeViewMdTitle::load_slot()
{
    QString s_file;
    QString s_size;
    if(cur_index.isValid())
    {
        QModelIndex index2 = tocModel->index(cur_index.row(), 1, cur_index.parent());
        s_file   = tocModel->data(cur_index,Qt::DisplayRole).toString();
        s_size   = tocModel->data(index2,Qt::DisplayRole).toString();

    }
    //获取所有的父类
    QStringList path;
    // 从子节点向上遍历到根节点
    QModelIndex index_scan = cur_index.parent();
    while (index_scan.isValid()) {
        // 获取当前节点的文本
        QString nodeText = index_scan.data(Qt::DisplayRole).toString();
        path.append(nodeText);

        // 移动到父节点
        index_scan = index_scan.parent();
    }
    std::reverse(path.begin(), path.end());//获取路径

    // 反转路径，从根节点到子节点
    std::reverse(path.begin(), path.end());

    //输出逻辑
    load_info.clear();
    load_info.append(s_file);
    load_info.append(s_size);
    load_info.append(path); //反馈加载的节点

    emit load_trig(load_info);
    //完成显示优化
    ui->ui_tree->expandAll();
    for (int i = 0; i < ui->ui_tree->model()->columnCount(); ++i)
    {
        ui->ui_tree->resizeColumnToContents(i);
    }
}

void QTreeViewMdTitle::save_slot()
{

    //获取所有的父类
    QStringList path;
    QModelIndex index2 = tocModel->index(cur_index.row(), 1, cur_index.parent());
    QString     s_size = tocModel->data(index2,Qt::DisplayRole).toString();

    // 从子节点向上遍历到根节点
    QModelIndex index_scan = cur_index;
    while (index_scan.isValid()) {
        // 获取当前节点的文本，选择文件名
        index_scan = tocModel->index(index_scan.row(), 0, index_scan.parent());
        QString nodeText = tocModel->data(index_scan,Qt::DisplayRole).toString();
        path.append(nodeText); //增加缓存的节点
        // 移动到父节点
        index_scan = index_scan.parent();
    }

    // 反转路径，从根节点到子节点
    std::reverse(path.begin(), path.end());

    //输出逻辑
    load_info.clear();
    load_info.append(""); //文件名
    load_info.append(s_size); //大小，用于判断当前节点是否是目录
    load_info.append(path); //反馈加载的节点

    emit save_trig(load_info); //发送信息到上层模块

    //完成显示优化
    ui->ui_tree->expandAll();
    for (int i = 0; i < ui->ui_tree->model()->columnCount(); ++i)
    {
        ui->ui_tree->resizeColumnToContents(i);
    }
}

void QTreeViewMdTitle::list_slot()
{
    QStringList str = {""};
    emit list_trig(str); //发送空字符串，替代之前的按钮
}


void QTreeViewMdTitle::on_ui_tree_clicked(const QModelIndex &index)
{
    cur_index = index;
}


void QTreeViewMdTitle::on_ui_tree_doubleClicked(const QModelIndex &index)
{
    // 判断索引是否有效
    if (!index.isValid()) {
        qDebug() << "无效的节点索引";
        return;
    }

    // 获取用户输入的新节点名称
    bool ok;
    QString nodeName = QInputDialog::getText(this,
                                           "添加节点",
                                           "请输入新节点名称:",
                                           QLineEdit::Normal,
                                           "新节点",
                                           &ok);

    // 如果用户点击了确定且输入不为空
    QModelIndex newIndex;
    if (ok && !nodeName.isEmpty()) {
        // 获取当前节点对应的Item
        QStandardItem *currentItem = tocModel->itemFromIndex(index);

        // 创建新节点
        QStandardItem *newItem = new QStandardItem(nodeName);

        // 将新节点添加为当前节点的子节点
        currentItem->appendRow(newItem);

        // 展开当前节点，以便看到新添加的子节点
        ui->ui_tree->expand(index);

        // 选中新添加的节点
        newIndex = tocModel->indexFromItem(newItem);
        ui->ui_tree->setCurrentIndex(newIndex);
    }

    //创建目录
    ui->ui_tree->expandAll();
    for (int i = 0; i < ui->ui_tree->model()->columnCount(); ++i)
    {
        ui->ui_tree->resizeColumnToContents(i);
    }
}

